--- layout: post title: 'Nginx 服务器的安装与配置' date: 2017-10-25 author: "zhubiao" header-img: "img/post-bg-universe.jpg" categories: Linux tags: Nginx ---
nginx 介绍
Nginx (“engine x”) 是一个自由、开源、高性能的HTTP和反向代理服务器( 作为HTTP, SMTP,POP3 和 IMAP反向代理服务器),该软件由 Igor Sysoev 创建,并于2004年首次公开发布。Nginx选择高性能的 epoll作为网络I/O模型,在高并发连接的情况下,Nginx 是 Apache 服务器不错的替代品,它能够支持高达 50000 个并发连接数的相应,而内存、CPU等资源消耗却非常低,运行非常稳定,解决了著名的C10K问题。中国大陆使用nginx或基于其做二次开发的网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。
nginx 安装
一、rpm包安装
rpm包下载地址
安装
此处使用官网的yum源安装
配置yum仓库
[12@root yum.repos.d]# cat nginx.repo
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1
安装
yum -y install nginx
二、源码编译安装
通过修改源码来自定义响应头部 Server 字段显示的名称和版本号。
[21@root src]# pwd
/usr/src
[21@root src]# ls
nginx-1.13.5.tar.gz
[21@root src]# tar -xf nginx-1.13.5.tar.gz
[21@root src]# cd nginx-1.13.5/
# 修改当设置了 "server_tokens off;" 时显示的软件名称
[21@root nginx-1.13.5]# vim src/http/ngx_http_header_filter_module.c
static u_char ngx_http_server_string[] = "Server: engine" CRLF;
# 修改未设置了 "server_tokens off;" 时显示的软件名称和版本号
[21@root nginx-1.13.5]# vim src/core/nginx.h
#define nginx_version 1020001
#define NGINX_VERSION "1.20.1"
#define NGINX_VER "zhuenginx/" NGINX_VERSION
# 创建用户
[21@root nginx-1.13.5]# useradd -s /sbin/nologin -r nginx
# 安装依赖包
[21@root nginx-1.13.5]# yum -y install openssl-devel pcre-devel
# 创建MakeFile文件
./configure \
--prefix=/usr/share/nginx \ #根目录
--sbin-path=/usr/sbin/nginx \ #主程序文件路径
--modules-path=/usr/lib64/nginx/modules \ #模块文件路径
--conf-path=/etc/nginx/nginx.conf \ #配置文件路径
--error-log-path=/var/log/nginx/error.log \ #错误日志文件路径
--http-log-path=/var/log/nginx/access.log \ #http日志文件路径
--http-client-body-temp-path=/var/lib/nginx/tmp/client_body \ #客户端主体文件临时存放路径
--http-proxy-temp-path=/var/lib/nginx/tmp/proxy \ #http反向代理服务器响应报文临时文件存放路径
--http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi \ #FastCGI反向代理服务器响应报文临时文件存放路径
--pid-path=/run/nginx.pid \ #pid文件路径
--lock-path=/run/lock/subsys/nginx \ #锁文件路径
--user=nginx \ #wroker进程发起者用户名
--group=nginx \ #wroker进程发起者组名
--with-file-aio \ #文件异步存储模块
--with-http_gunzip_module \ #gunzip压缩模块
--with-http_gzip_static_module \ #gzip压缩模块
--with-http_stub_status_module \ #服务器信息显示模块
--with-pcre \ #支持正则匹配模块
--with-stream=dynamic \
--with-stream_ssl_module \
--with-debug
# 编译安装
[21@root nginx-1.13.5]# make && make install
三、启动 nginx
nginx
nginx -s reload
nginx -t
nginx -s stop
nginx 配置文件结构
/etc/nginx/nginx.conf
nginx 配置
一、正常运行必备的配置
Syntax: user user [group];
Default: user nobody nobody;
Context: main
Syntax: pid file;
Default: pid nginx.pid;
Context: main
Syntax: include file | mask;
Default: —
Context: any
# example
include /etc/nginx/default.d/*.conf;
Syntax: load_module file;
Default: —
Context: main
# example
load_module "/usr/lib64/nginx/modules/ngx_stream_module.so";
二、性能优化相关的配置
Syntax: worker_processes number | auto;
Default: worker_processes 1;
Context: main
Syntax: worker_cpu_affinity cpumask ...;
worker_cpu_affinity auto [cpumask];
Default: —
Context: main
# example
# 1. 4颗CPU,启动4个worker进程,将每个进程分别与CPU0, CPU1, CPU2, CPU3绑定
worker_processes 4;
worker_cpu_affinity 0001 0010 0100 1000;
# 2. 4颗CPU,启动2个worker进程,第一个进程绑定到CPU0/CPU2上,第二个进程绑定到CPU1/CPU3上
worker_process 2;
worker_cpu_affinity 0101 1010;
# 3. 自动绑定
worker_process auto;
worker_cpu_affinity auto;
[-20,19]Syntax: worker_priority number;
Default: worker_priority 0;
Context: main
# example
worker_priority -10
Syntax: worker_rlimit_nofile number;
Default: —
Context: main
# example
worker_rlimit_nofile 30000
三、事件驱动相关的配置
events {
...
}
worker_connections设定的数值不能大于另外一个指令worker_rlimit_nofile number (worker进程最大打开文件数)所设定的值Syntax: worker_connections number;
Default: worker_connections 1024;
Context: events
Syntax: use method;
Default: —
Context: events
# example
use epoll
accept_mutex 为 on时,有新的连接请求,worker进程轮流处理,否则将通知所有进程,造成”惊群”,效率低下。Syntax: accept_mutex on | off;
Default: accept_mutex off;
Context: events
# example
accept_mutex on;
四、调试和定位问题
Syntax: daemon on | off;
Default: daemon on;
Context: main
Syntax: master_process on | off;
Default: master_process on;
Context: main
master_process 为 on 时,nginx会启动一个master主进程,master主进程fork()出一个或多个worker子进程,此种情况下makster进程充当监控程序,通过信号通知worker进程处理用户的连接请求。若设定为 off,master进程将自己处理所有业务。

debug, info, notice, warn, error, crit, alert, emerg,指定某错误级别后,该级别及更严重级别的消息将记录于错误日志中。Syntax: error_log file [level];
Default: error_log logs/error.log error;
Context: main, http, mail, stream, server, location
# example
error_log /var/log/nginx/error.log error;
五、http协议配置段格式
http
{
... ...
server
{
... ...
location [ = | ~ | ~* | ^~ ] uri
{
... ...
}
}
server
{
... ...
}
}
六、与套接字相关配置
Syntax: listen {address[:port]|port|unix:path} [default_server] [ssl] [backlog=number] [rcvbuf=size] [sndbuf=size];
Default: listen *:80 | *:8000;
Context: server
---
default_server #设定为默认虚拟主机
ssl #限制必须通过ssl连接才提供服务
backlog=number #超过最大并发连接数后,设定新请求进入队列的最大值
rcvbuf=size #接收缓冲区的大小
sendbuf=size #发送缓冲区的大小
# example
listen 127.0.0.1:8000;
listen 127.0.0.1;
listen 8000;
listen *:8000;
listen localhost:8000;
listen unix:/var/run/nginx.sock;
listen 127.0.0.1:8000 default_server;
Syntax: server_name name ...;
Default: server_name "";
Context: server
---
1. 支持 “*” 通配符
*.zhubiaook.com www.zhubiaook.*
2. 支持正则表达, 要使用正则匹配,在模式前加符号“~”
~^www\d+\.zhubiaook\.com$
3. 各种模式的优先级
精确匹配 : www.zhubiaook.com
左侧通配符 : *.zhubiaook.com
右侧通配符 : www.zhubiaook.com
正则表达式 : ~^www\d+\.zhubiaook\.com$
default_server : 均为匹配到以上主机名,则使用默认监听套接字的虚拟主机
# example
server {
server_name zhubiaook.com www.zhubiaook.com;
}
server {
server_name *.zhubiaook.com www.zhubiaook.*;
}
server {
server_name www.zhubiaook.com ~^www\d+\.zhubiaook\.com$;
}
Syntax: root path;
Default: root html;
Context: http, server, location, if in location
# example
http
{
# 所有主机默认的主站点目录
root /app/web
server
{
# 特定主机的主站点目录
root /data/html
location /images/ {
# uri为/images/时的主站点目录:/images/picture/
root /picture
}
}
}
[11@root conf.d]# cat virtual.conf
# A virtual host using of name-based configuration
server {
listen 80;
server_name www.zhubiaook.com;
root /app/web1;
index index.html index.htm;
}
server {
listen 80;
server_name blog.zhubiaook.com;
root /app/web2;
index index.html index.htm;
}
基于端口的虚拟主机
[11@root conf.d]# cat virtual.conf
# A virtual host using of port-based configuration
server {
listen 80 default_server;
root /app/web1;
index index.html index.htm;
}
server {
listen 8080;
root /app/web2;
index index.html index.htm;
}
基于IP的虚拟主机
[11@root conf.d]# cat virtual.conf
# A virtual host using of IP-based configuration
server {
listen 172.18.17.11:80;
root /app/web1;
index index.html index.htm;
}
server {
listen 192.168.17.11:80;
root /app/web2;
index index.html index.htm;
}
Syntax: sendfile on | off;
Default: sendfile off;
Context: http, server, location, if in location
传统数据拷贝方法
使用sendfile功能的数据拷贝方法

参考文献:通过零拷贝实现有效数据传输
Syntax: tcp_nodelay on | off;
Default: tcp_nodelay on;
Context: http, server, location
Syntax: server_tokens on | off | build | string;
Default: server_tokens on;
Context: http, server, location
---
on #Server: nginx/1.12.1
off #Server: nginx
build #可以在编译安装时加入选项 --build=NAME,将会在版本中加入添加的名字
e.g
--build=zhubiao
Server: nginx/1.12.1 (zhubiao)
# 我们也可以修改源码,来修改显示的服务器名
修改源码文件 nginx-1.12.1/src/core/nginx.h 下面的内容:
#define NGINX_VER "Zegine/" NGINX_VERSION
编译安装后的名字:Server: Zegine/1.12.1
Syntax: location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }
Default: —
Context: server, location
---
# 以下排序按优先级高低从上到下排序:
= : 对uri做精确匹配,即相同才匹配
^~ : 对uri左侧做正则匹配
~ : 对uri做正则匹配
~* : 对uri做正则匹配,不区分大小写
不带符号 : 匹配左侧字符串
# example
location = /f1 {
[ configuration A ]
}
location / {
[ configuration B ]
}
location /documents/ {
[ configuration C ]
}
location ^~ /images/ {
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {
[ configuration E ]
}
The “/f1” request will match configuration A,
the “/index.html” request will match configuration B,
the “/documents/document.html” request will match configuration C,
the “/images/1.gif” request will match configuration D,
the “/documents/1.jpg” request will match configuration E.
Syntax: alias path;
Default: —
Context: location
# example
location /image/ {
alias /app/web1/picture/;
}
Syntax: index file ...;
Default: index index.html;
Context: http, server, location
# exapmple
index index.$geo.html index.0.html /index.html;
Syntax: error_page code ... [=[response]] uri;
Default: —
Context: http, server, location, if in location
# example
error_page 501 502 503 503 =200 /50x.html
location = /50x.html {
root /app/web/error;
}
Syntax: try_files file ... uri;
try_files file ... =code;
Default: —
Context: server, location
# example
location / {
root /app/web1;
try_files $uri $uri/index.html $uri/index.php;
}
location /images/ {
root /app/web1;
try_files $uri /picture/index.jpg1 =404;
}
Syntax: stub_status;
Default: —
Context: server, location
---
# 显示的信息
Active connections: 1
server accepts handled requests
15 15 16
Reading: 0 Writing: 1 Waiting: 0
# example
location /status {
stub_status;
}
七、客户端请求相关配置
Syntax: keepalive_disable none | browser ...;
Default: keepalive_disable msie6;
Context: http, server, location
Syntax: keepalive_timeout timeout [header_timeout];
Default: keepalive_timeout 75s;
Context: http, server, location
---
timeout #保持长连接的时间
[header_timeout] #设定相应头部显示的长连接时间 Keep-Alive:timeout=TIME
Syntax: keepalive_requests number;
Default: keepalive_requests 100;
Context: http, server, location
Syntax: send_timeout time;
Default: send_timeout 60s;
Context: http, server, location
Syntax: client_body_temp_path path [level1 [level2 [level3]]];
Default: client_body_temp_path client_body_temp;
Context: http, server, location
---
level1 #指定一级子目录由几个16进制数组成
level2 #指定二级子目录由几个16进制数组成
# example
client_body_temp_path /app/nginx/client_temp 1 2
Syntax: client_body_buffer_size size;
Default: client_body_buffer_size 8k|16k;
Context: http, server, location
# example
client_body_buffer_size 8k;
八、对客户端进行限制的相关配置
Syntax: limit_rate rate;
Default: limit_rate 0;
Context: http, server, location, if in location
Syntax: limit_except method ... { ... }
Default: —
Context: location
---
method #GET, HEAD, POST, PUT, DELETE, MKCOL, COPY, MOVE, OPTIONS, PROPFIND, PROPPATCH, LOCK, UNLOCK, or PATCH
# example
# 除了192.168.1.0/24网段可以使用任何请求方法,其它网段的只能使用GET请求方法
limit_except GET {
allow 192.168.1.0/24;
deny all;
}
九、文件操作优化配置
Syntax: aio on | off | threads[=pool];
Default: aio off;
Context: http, server, location
Syntax: directio size | off;
Default: directio off;
Context: http, server, location
Syntax: open_file_cache off;
open_file_cache max=N [inactive=time];
Default: open_file_cache off;
Context: http, server, location
Syntax: open_file_cache_errors on | off;
Default: open_file_cache_errors off;
Context: http, server, location
Syntax: open_file_cache_min_uses number;
Default: open_file_cache_min_uses 1;
Context: http, server, location
Syntax: open_file_cache_valid time;
Default: open_file_cache_valid 60s;
Context: http, server, location
十、访问控制
基于IP的访问控制
Syntax: allow address | CIDR | unix: | all;
Default: —
Context: http, server, location, limit_except
Syntax: deny address | CIDR | unix: | all;
Default: —
Context: http, server, location, limit_except
location / {
deny 192.168.1.1;
allow 192.168.1.0/24;
allow 10.1.1.0/16;
allow 2001:0db8::/32;
deny all;
}
基于用户名和密码的访问控制
Syntax: auth_basic string | off;
Default: auth_basic off;
Context: http, server, location, limit_except
Syntax: auth_basic_user_file file;
Default: —
Context: http, server, location, limit_except
# 1. 安装创建加密用户名和密码的工具httpd-tools
yum -y install httpd-tools
# 2. 创建用户
[11@root conf.d]# htpasswd -c /etc/nginx/conf.d/nginx_user zhubiao
New password:
Re-type new password:
Adding password for user zhubiao
# 3. 修改配置文件
location = / {
auth_basic "www.zhubiaook.com";
auth_basic_user_file /etc/nginx/conf.d/nginx_user;
root /app/web1;
index index.html;
}

十一、定义日志
Syntax: log_format name [escape=default|json] string ...;
Default: log_format combined "...";
Context: http
# example
log_format delog '$remote_addr - $remote_user [$time_local] "$request" ';
Syntax: access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
access_log off;
Default: access_log logs/access.log combined;
Context: http, server, location, if in location, limit_except
# example
access_log /var/log/nginx/access.log delog;
Syntax: open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];
open_log_file_cache off;
Default: open_log_file_cache off;
Context: http, server, location
---
max=N #文件元数据的缓存数量,超过此值将使用LRU算法删除最少使用的
[inactive=time] #设定时长,在此时间内为未被使用将删除被缓存的文件元数据
[min_uses=N] #在inactive指定的时间内最少被使用多少次才激活为活动项
[valid=time] #检查的时间间隔
# example
open_log_file_cache max=1000 inactive=20s valid=1m min_uses=2;
十二、gzip相关的配置
Syntax: gzip on | off;
Default: gzip off;
Context: http, server, location, if in location
[1,9]Syntax: gzip_comp_level level;
Default:
gzip_comp_level 1;
Context: http, server, location
Syntax: gzip_disable regex ...;
Default: —
Context: http, server, location
Syntax: gzip_min_length length;
Default: gzip_min_length 20;
Context: http, server, location
Syntax: gzip_http_version 1.0 | 1.1;
Default: gzip_http_version 1.1;
Context: http, server, location
Syntax: gzip_buffers number size;
Default: gzip_buffers 32 4k|16 8k;
Context: http, server, location
Syntax: gzip_types mime-type ...;
Default: gzip_types text/html;
Context: http, server, location
Syntax: gzip_vary on | off;
Default: gzip_vary off;
Context: http, server, location
Syntax: gzip_proxied off | expired | no-cache | no-store | private | no_last_modified | no_etag | auth | any ...;
Default: gzip_proxied off;
Context: http, server, location
[11@root conf.d]# ll /app/web/messages.txt
-rw-r--r-- 1 root root 1348498 Aug 21 03:07 /app/web/messages.txt
[11@root conf.d]# cat /etc/nginx/conf.d/zhubiao.conf
server {
listen 80 default_server;
root /app/web;
location / {
# Compresses responses using the "gzip"
gzip on;
gzip_comp_level 9;
gzip_min_length 1024;
gzip_http_version 1.0;
gzip_buffers 16 8k;
gzip_proxied any;
gzip_types text/xml text/plain;
gzip_vary on;
}
}
[11@root conf.d]# nginx -s reload

十三、ssl相关的配置
Syntax: ssl on | off;
Default: ssl off;
Context: http, server
Syntax: ssl_certificate file;
Default: —
Context: http, server
Syntax: ssl_certificate_key file;
Default: —
Context: http, server
Syntax: ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2] [TLSv1.3];
Default: ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
Context: http, server
Syntax: ssl_session_cache off | none | [builtin[:size]] [shared:name:size];
Default: ssl_session_cache none;
Context: http, server
---
off #不使用缓存,并明确告知客户端缓存不可使用
none #告诉客户端缓存可用,实际服务器没有缓存
[builtin[:size]] #OpenSSl内建缓存,为每个worker进程独有,如果大小不指定,默认为20k,使用OpenSSl内建缓存会导致内存碎片
[shared:name:size] #所有worker进程共享一个缓存,1M的内存可以存储4000个会话。
Syntax: ssl_session_timeout time;
Default: ssl_session_timeout 5m;
Context: http, server
www.zhubiaook.com的私钥和证书文件[11@root conf.d]# cd /etc/pki/tls/certs/
[11@root certs]# make zhubiaook.crt
...
Enter pass phrase:
Verifying - Enter pass phrase:
...
Enter pass phrase for zhubiaook.com.key:
...
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:yunnan
Locality Name (eg, city) [Default City]:xuanwei
Organization Name (eg, company) [Default Company Ltd]:zhubiaook.com
Organizational Unit Name (eg, section) []:IT
Common Name (eg, your name or your server's hostname) []:www.zhubiaook.com
Email Address []:
b. 创建站点www.moretz.com的私钥和证书文件
[11@root certs]# make moretz.crt
...
Verifying - Enter pass phrase:
...
Enter pass phrase for moretz.key:
...
Country Name (2 letter code) [XX]:US
State or Province Name (full name) []:georgia
Locality Name (eg, city) [Default City]:Atlanta
Organization Name (eg, company) [Default Company Ltd]:moretz.com
Organizational Unit Name (eg, section) []:performer
Common Name (eg, your name or your server's hostname) []:www.moretz.com
Email Address []:
c. 复制证书文件到/etc/nginx/conf.d/ssl目录下,并去除私钥加密密码
[11@root certs]# mkdir /etc/nginx/conf.d/ssl
[11@root certs]# cp zhubiaook* moretz* /etc/nginx/conf.d/ssl/
[11@root certs]# cd /etc/nginx/conf.d/ssl/
[11@root ssl]# openssl rsa -in zhubiaook.key -out zhubiaook.key
Enter pass phrase for zhubiaook.com.key:
writing RSA key
[11@root ssl]# openssl rsa -in moretz.key -out moretz.key
Enter pass phrase for moretz.key:
writing RSA key
[11@root ssl]# mv zhubiaook.com.crt zhubiaook.crt
[11@root ssl]# ls
moretz.crt moretz.key zhubiaook.com.key zhubiaook.crt zhubiaook.key
d. 创建配置文件
[11@root conf.d]# cat /etc/nginx/conf.d/ssl.conf
server {
listen 443 ssl;
server_name www.zhubiaook.com;
root /app/web1;
ssl on;
ssl_certificate /etc/nginx/conf.d/ssl/zhubiaook.crt;
ssl_certificate_key /etc/nginx/conf.d/ssl/zhubiaook.key;
ssl_session_cache shared:SSLZ:1m;
ssl_session_timeout 10m;
}
server {
listen 443 ssl;
server_name www.moretz.com;
root /app/web2;
ssl on;
ssl_certificate /etc/nginx/conf.d/ssl/moretz.crt;
ssl_certificate_key /etc/nginx/conf.d/ssl/moretz.key;
ssl_session_cache shared:SSLM:1m;
ssl_session_timeout 10m;
}
e. 导入证书
十四、URI重定向
Syntax: rewrite regex replacement [flag];
Default: —
Context: server, location, if
---
flag:
last #在本条匹配的rewrite规则执行完后,对所其所在的标签再次发起请求;
break #在本条匹配的rewrite规则执行完后,终止匹配;
redirect #返回302临时重定向给客户端,客户端再次通过返回的地址发起请求
permanent #返回301永久定向给客户端,客户端再次通过返回的地址发起请求
# example
server {
listen 80 default_server;
root /app/web;
location / {
rewrite ^/(.*)$ /images/$1 break;
}
}
server {
listen 80 default_server;
root /app/web;
rewrite ^/(.*)$ https://www.moretz.com/$1 redirect;
}
Syntax: return code [text];
return code URL;
return URL;
Default: —
Context: server, location, if
# example
location / {
return 301 https://www.zhubiaook.com;
}
server {
listen 80 default_server;
root /app/web;
location / {
return 404;
}
error_page 404 /404.html;
location = /404.html {
root /app/web/error;
ngx_http_rewrite_module启用日志记录功能,并将其记录到error_log中。Syntax: rewrite_log on | off;
Default: rewrite_log off;
Context: http, server, location, if
Syntax: set $variable value;
Default: —
Context: server, location, if
Syntax: if (condition) { ... }
Default: —
Context: server, location
---
condition:
比较操作符
==, != #比较字符串是否相同
~, !~ #是否匹配字符串(使用正则表达式),区分大小写
~*, !~* #是否匹配字符串(使用正则表达式),不区分大小写
文件存在性判断
-e, !-e #判断文件(普通文件,目录,符号链接...)是否存在
-f, !-f #判断普通文件是否存在
-d, !-d #判断目录是否存在
-x, !-x #判断文件是否可执行
十五、防盗链
$invalid_referer的值是空,还是1Syntax: valid_referers none | blocked | server_names | string ...;
Default: —
Context: server, location
---
none #请求报文头部中没有Referer字段
blocked #请求报文头部有Referer字段,但没有值,比如被反代理服务器删除。
server_names #请求报文头部有Referer字段,并且包含本主机的主机名
string #匹配请求报文头部Referer字段的值
[11@root conf.d]# cat zhubiao.conf
server {
listen 80 default_server;
root /app/web1;
server_name www.zhubiaook.com;
}
server {
listen 80;
root /app/web2;
server_name www.moretz.com;
valid_referers none block server_names ~\.baidu\.;
if ($invalid_referer){
return 404;
}
error_page 404 /404.html;
location = /404.html {
alias /app/web2/404.html;
}
}
十五、反向代理
反向代理模块Module ngx_http_proxy_module可以将用户的请求转移到后端的服务器上。
Syntax: proxy_pass URL;
Default: —
Context: location, if in location, limit_except
---
# example
# 对匹配到的uri掉度到 http://host[:port]/uri
location /uri/ {
proxy_pass http://host[:port]
}
# 对匹配到的uri掉度到 http://host[:port]
location /uri/ {
proxy_pass http://host[:port]/
}
Syntax: proxy_set_header field value;
Default: proxy_set_header Host $proxy_host;
proxy_set_header Connection close;
Context: http, server, location
# example
proxy_set_header Real_IP $remote_addr;
proxy_set_header Forward_For $proxy_add_x_forwarded_for;
Syntax: proxy_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size];
Default: —
Context: http
---
path #缓存路径
levels #缓存在磁盘上存储的目录层次和数量
keys_zone #缓存区域名称和大小
inactive #非活动时间
max_size #proxy缓存大小
# example
proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=one:10m;
proxy_cache_path 所定义的缓存区Syntax: proxy_cache zone | off;
Default: proxy_cache off;
Context: http, server, location
---
zone # proxy_cache_path 参数keys_zone=name:size所定义的区域名称
Syntax: proxy_cache_key string;
Default: proxy_cache_key $scheme$proxy_host$request_uri;
Context: http, server, location
Syntax: proxy_cache_valid [code ...] time;
Default: —
Context: http, server, location
Syntax: proxy_cache_use_stale error | timeout | invalid_header | updating | http_500 | http_502 | http_503 | http_504 | http_403 | http_404 | http_429 | off ...;
Default: proxy_cache_use_stale off;
Context: http, server, location
Syntax: proxy_cache_methods GET | HEAD | POST ...;
Default: proxy_cache_methods GET HEAD;
Context: http, server, location
Syntax: proxy_hide_header field;
Default: —
Context: http, server, location
Syntax: proxy_connect_timeout time;
Default: proxy_connect_timeout 60s;
Context: http, server, location
Syntax: proxy_send_timeout time;
Default: proxy_send_timeout 60s;
Context: http, server, location
Syntax: proxy_read_timeout time;
Default: proxy_read_timeout 60s;
Context: http, server, location
十六、自定义首部
模块ngx_http_headers_module 用于给客户端发送的响应报文头部中添加自定义的头部字段。
Syntax: add_header name value [always];
Default: —
Context: http, server, location, if in location
Syntax: add_trailer name value [always];
Default: —
Context: http, server, location, if in location
十七、FastCGI
模块ngx_http_fastcgi_module 实现将请求转发给后端FastCGI服务器,比如PHP-FPM服务器。
Syntax: fastcgi_pass address;
Default: —
Context: location, if in location
# exapmple
fastcgi_pass localhost:9000;
Syntax: fastcgi_index name;
Default: —
Context: http, server, location
# example
fastcgi_index index.php;
Syntax: fastcgi_param parameter value [if_not_empty];
Default: —
Context: http, server, location
# example
fastcgi_param SCRIPT_FILENAME /home/www/scripts/php$fastcgi_script_name;
fastcgi_param QUERY_STRING $query_string;
Syntax: fastcgi_cache_path path [levels=levels] keys_zone=name:size [inactive=time] [max_size=size];
Default: —
Context: http
fastcgi_cache_path 所定义的缓存区Syntax: fastcgi_cache zone | off;
Default: fastcgi_cache off;
Context: http, server, location
Syntax: proxy_cache_key string;
Default: proxy_cache_key $scheme$proxy_host$request_uri;
Context: http, server, location
Syntax: fastcgi_cache_methods GET | HEAD | POST ...;
Default: fastcgi_cache_methods GET HEAD;
Context: http, server, location
Syntax: fastcgi_cache_min_uses number;
Default: fastcgi_cache_min_uses 1;
Context: http, server, location
fastcgi_keep_conn设置为on时,nginx服务器将通知FastCGI服务器保持连接,对于长连接,这种设置很有必要。Syntax: fastcgi_keep_conn on | off;
Default: fastcgi_keep_conn off;
Context: http, server, location
10 .针对于不同响应状态码设置不同的缓存时间
Syntax: fastcgi_cache_valid [code ...] time;
Default: —
Context: http, server, location
# example
fastcgi_cache_valid 200 302 10m;
fastcgi_cache_valid 404 1m;
十八、负载均衡
模块 ngx_http_upstream_module 用于将多台后端服务器组合成一个服务器组,这个服务器组可以被 proxy_pass, fastcgi_pass, uwsgi_pass, scgi_pass 和 memcached_pass 命令调用,从而达到组中的服务器共同承担负载的功能,实现负载均衡。
Syntax: upstream name { ... }
Default: —
Context: http
# example
upstream backend {
server backend1.example.com weight=5;
server 127.0.0.1:8080 max_fails=3 fail_timeout=30s;
server backup1.example.com backup;
}
Syntax: server address [parameters];
Default: —
Context: upstream
---
[parameters]
weight=number #权重
max_conns=number #最大并发连接数
max_fails=number #连接失败的尝试次数,超出后将标记为不可用
fail_timeout=time #连接失败的超时时间,超出后将标记为不可用
backup #标记为备用,其它服务器全部宕机后才启用
down #标记为不可用
Syntax: keepalive connections;
Default: —
Context: upstream
调度算法
Syntax: ip_hash;
Default: —
Context: upstream
Syntax: least_conn;
Default: —
Context: upstream
Syntax: hash key [consistent];
Default: —
Context: upstream
十九、实现传输层TCP/UDP的反向代理或负载均衡
Syntax: stream { ... }
Default: —
Context: main
配置文件
[20@root nginx]# vim /etc/nginx/nginx.conf
...
stream {
upstream mysqlservers {
server 172.18.17.10:3306;
server 172.18.17.21:3306;
}
server {
listen 172.18.17.20:3306;
proxy_pass mysqlservers;
proxy_timeout 60s;
proxy_connect_timeout 10s;
}
}
测试
本节完,后面的博客将以一个综合性的实验来演示上面的配置,请看后文。